﻿Ext.ns('Mdm');

/* Show dialog for passed dialog (or id of window)
 * Parameters:
 * dialog - Either an instance of dialog window or ID
 *		of component representing dialog window
 * args - Arguments taht should be passed to window eg.
 *		{foo: 'bar', id: 1}
 */
function showDialog(dialog, args){

    alert('This function is obsolete! Use sio:Dialog and call #{DialogId}.show()');
    return;
	if(typeof(dialog) == 'String'){
		dialog = Ext.getCmp(dialog);
	}
	
	try{
		var url = dialog.url;

		if(args){
			if(typeof(args) == 'String'){
				url = Ext.urlAppend(url, args);
			} else {
				url = Ext.urlAppend(url, Ext.urlEncode(args));
			}
		}
		
		dialog.loadIFrame({
			url: url,
			showMask: true,
			text: 'Loading...',
			scripts: true
		});
		
		dialog.show();
		
		// TODO: Call dialogclosed when we get Ext.Net example of how to
		// implement custom direct methods
//		dialog.on('hide', function(el){
//			dialog.un('hide');
//			dialog.fireEvent('dialogclosed');
//			//debugger;
//		});
		
	}catch(e){
		// TODO: Remove for release
		debugger;
		alert('Excpetion showing dialog ' + e.what);
	}
};

/* Confirm action on button before action may proceede
 * button - instance of button to confirm before action
 *		is performed
 */
function allowAction(button){
	if(!button || button.confirmed){
		return;
	}
	
	Ext.Msg.confirm('IDM', button.confirmMsg || 'Proceed?', function(btn){
		button.confirmed = btn == 'yes';
		if(button.confirmed){
			button.fireEvent('click');
			button.confirmed = false;
		}
	});
};

/*
 * Open tab in parent tab panel.
 * Parameters:
 *  url - url of aspx page to open
 *  args -  Arguments taht should be passed to tab eg.
 *		{foo: 'bar', id: 1}
 *  tabID - unique ID to avoid duplicates
 */
function openTab(url, title, args, tabId) {
    var elements = parent.Ext.select('div[tabParent=true]').elements;

    if (!elements.length) {
        return;
    }

    if (args) {
        if (typeof (args) == 'String') {
            url = Ext.urlAppend(url, args);
        } else {
            url = Ext.urlAppend(url, Ext.urlEncode(args));
        }
    }

    var tabPanel = null;
    
    if (Ext.isGecko) {
        tabPanel = elements[0];   //parent.Ext.getCmp(elements[0].id); // .firstChild.nextSibling.id);
    }
    else if (Ext.isChrome) {
        tabPanel = elements[0];
    }
    else {
        tabPanel = parent.Ext.getCmp(elements[0].firstChild.id);
    }

    var index = tabPanel.id.indexOf('_');

    if (index > -1) {        
        tabPanel = parent.Ext.getCmp(tabPanel.id.substring(0, index));
    }

    parent.Ext.net.DirectMethods.OpenTab(tabPanel.id, url, title, tabPanel.items.length, tabId);
}

Ext.override(Ext.grid.GridPanel, {
    firstLayout: true,
    lastHeight: 0,
    initStateEvents: Ext.grid.GridPanel.prototype.onResize.createInterceptor(function() {
        if (this.enableRowResize) {
            this.store.autoLoad = false;
            this.store.on('beforeload', this.onBeforeLoad, this);
        }
        return true;
    }),
    onBeforeLoad: function(s, options) {

        if (this.firstLayout) {
            this.on('afterlayout', this.onAfterLayout, this, { buffer: 250 });
            this.firstLayout = false;
        }

        var items = this.getItemsCountPerPage();

        if (items < 1) {
            return;
        }

        // This should prevent flickering
        this.lastHeight = this.getEl().getHeight();

        options.params.limit = items;
        options.params.cacheId = this.cacheId;
        
        var bar = this.getPagingBar();
        if (bar) {
            bar.pageSize = items;
        }
    },
    onAfterLayout: function() {
        if (this.firstLayout) {
            this.firstLayout = false;
            return;
        }

        if (this.getEl().getHeight() == this.lastHeight) {
            return;
        }
        this.lastHeight = this.getEl().getHeight();

        var s = this.getStore()
        if (s) { s.reload(); }
    },
    getItemHeight: function() {
        var s = this.getStore();

        if (!s.getCount()) {
            return this.rowHeight;
        }

        return Ext.get(this.getView().getRow(0)).getHeight();
    },
    getPagingBar: function() {
        var tbar = this.getTopToolbar();
        var bbar = this.getBottomToolbar();

        if (tbar && tbar.xtype == 'paging') {
            return tbar;
        }
        if (bbar && bbar.xtype == 'paging') {
            return bbar;
        }

        return null;
    },
    getItemsCountPerPage: function() {
        var view = this.getView();
        var diff = view.el.getHeight() - Ext.get(view.innerHd).getHeight();
        return Math.floor(diff / this.getItemHeight());
    }
});

Mdm.Window = function(config) {

    this.windowConfig = Ext.apply({}, config);
    this.addEvents('clientnotify');

    if (parent == window) {
        this.windowConfig.id = config.id + '_KremplusRex';
    }

    //    Ext.each(top.Ext.Window.prototype, function(a, el, c) {
    //        debugger;
    //        if (!el.createInterceptor) {
    //            return;
    //        }
    //        debugger;
    //        el = el.createInterceptor(function(a, b, c, d, e, f) {
    //            if (this.window) {
    //                debugger;
    //                el(a, b, c, d, e, f);
    //                //return Ext.apply(this.window, el);
    //                return false;
    //            }
    //            return true;
    //        }, this);
    //    }, this);

    // we're just dummy window so make sure we're hidden
    config.hidden = true;
    config.width = config.height = 0;
    config.autoLoad = null;

    Mdm.Window.superclass.constructor.call(this, config);
}


Ext.extend(Mdm.Window, Ext.Window, {
    windowConfig: null,
    window: null,

    show: function() {
        this.ensureWindow();
        this.window.show();
    },
    hide: function() {
        if (!this.window) {
            return;
        }
        this.window.hide();
    },
    close: function() {
        if (!this.window) {
            return;
        }
        this.window.close();
        this.window = null;
    },
    setTitle: function(title, iconCls) {
        if (this.window) {
            this.window.setTitle(title, iconCls);
        }
    },
    addParameter: function(name, value) {
        // UROS: super duper patch (2010-12-01)
        var param;

        // JURE: changed expression to support object type
        if (typeof (value) == 'string') {
            param = eval('Ext.apply({}, {' + name + ':"' + value + '"});');
        }
        else {
            param = eval('Ext.apply({}, {' + name + ':' + value + '});');
        }

        if (this.window) {
            this.window.autoLoad.params =
                Ext.apply(this.window.autoLoad.params, param);
        }

        this.windowConfig.autoLoad.params =
            Ext.apply(this.windowConfig.autoLoad.params, param);
    },

    // private
    ensureWindow: function() {
        if (this.window) {
            return;
        }
        this.windowConfig.renderTo = top.Ext.getBody();
        this.window = new top.Ext.Window(this.windowConfig);
        this.window.addEvents('clientmessage');

        // make sure we release pointer to internal window
        this.window.on('destroy', function() {
            Ext.util.Observable.releaseCapture(this.window);
            delete this.window;
            this.window = null;
        }, this);

        // just to copy (actually assign) some pointers that are not accessible until
        // after window has been rendered
        this.window.on('show', function() {
            this.buttons = this.window.buttons;
            this.tools = this.window.tools;
        }, this, { single: true });

        // capture events on internal window and relay it to this instance
        Ext.util.Observable.capture(this.window, function(ev, a, b, c, d, e, f, g, h) {
            return this.fireEvent(ev, a, b, c, d, e, f, g, h);
        }, this);

        // eat up all events on this instance
        Ext.util.Observable.capture(this, function() { return false; });
    },
    // protected
    onRender: function(ct, pos) {
        Ext.Window.superclass.onRender.call(this, ct, pos);
        if (!this.windowConfig.hidden || this.windowConfig.autoShow) {
            this.show();
        }
    }
});

Mdm.WindowProxy = function(config) {

    this.addEvents('buttonclicked');
    Mdm.WindowProxy.superclass.constructor.call(this, config);
}

Ext.extend(Mdm.WindowProxy, Ext.Component, {
    window: null,

    show: function() {
        if (this.window) {
            this.window.show();
        }
    },
    hide: function() {
        if (this.window) {
            this.window.hide();
        }
    },
    close: function() {
        if (this.window) {
            this.window.close();
            this.window = null;
        }
    },
    setTitle: function(title, iconCls) {
        if (this.window) {
            this.window.setTitle(title, iconCls);
        }
    },
    disableButton: function(buttonType, disable) {
        Ext.each(this.buttons, function(btn) {
            if (buttonType.indexOf(btn.buttonType) > -1) {
                btn.setDisabled(disable);
            }
        }, this);
    },
    addParameter: function(name, value) {
        if (!this.window) {
            return;
        }
        this.window.addParameter(name, value);
    },
    callParent: function(a, b, c, d, e, f, g) {
        if (this.window) {
            //            var args = Array.prototype.slice.call(arguments, 0);
            //            this.window.fireEvent.apply(this.window.fireEvent, args);
            //('clientnotify', this.window, (Array.prototype.slice.call(arguments, 0)));
            this.window.fireEvent('clientnotify', this.window, a, b, c, d, e, f, g);
        }
    },

    // protected
    onRender: function(ct, pos) {
        Mdm.WindowProxy.superclass.onRender.call(this, ct, pos);
        if (this.windowId) {
            this.window = parent.Ext.getCmp(this.windowId);

            if (!this.window) {
                this.window = parent.Ext.getCmp(this.windowId + '_KremplusRex');
            }

            this.window.windowProxy = this;

            // make sure we release pointer to internal window
            this.window.on('destroy', function() {
                Ext.util.Observable.releaseCapture(this.window);
                delete this.window;
                this.window = null;
            }, this);

            this.buttons = this.window.buttons;

            Ext.each(this.buttons, function(btn) {
                btn.on('click', function() { this.fireEvent('buttonclicked', btn) }, this);
            }, this);

            Ext.util.Observable.capture(this.window, function(ev, a, b, c, d, e, f, g, h) {
                return this.fireEvent(ev, a, b, c, d, e, f, g, h);
            }, this);
        }
    }
});

Mdm.FormPanel = function(config) {
    Mdm.FormPanel.superclass.constructor.call(this, config);
}

Ext.extend(Mdm.FormPanel, Ext.form.FormPanel, {
    onRender: function(ct, pos) {
        Mdm.FormPanel.superclass.onRender.call(this, ct, pos);

        if (this.markInvalidOnLoad) {
            (function() {
                Ext.each(this.getForm().items.items, function(el) {
                    if (!el.isValid()) {
                        el.getEl().addClass('x-form-invalid');
                    }
                });
            }).defer(500, this);
        }
    }
});

Ext.reg('mdmformpanel', Mdm.FormPanel);

/* Overriden to show message box in toplevel window instead in frames */
Ext.MessageBox.show = Ext.MessageBox.show.createInterceptor(function(options) {

    if (top == window) {
        return true;
    }

    top.Ext.MessageBox.show(options);
    return false;
});